const fs = require('fs-extra');
const path = require('path');
// const rename = think.promisify(fs.rename, fs);

const BaseRest = require('./rest.js');

module.exports = class extends BaseRest {
  async getAction() {
    let data;
    const map = {};
    
    if (this.id) {
      data = this.modelInstance.where({
        id: this.id,
      }).field('id,base_url,path').find();
      return this.success(data);
    }
    
    // 关键词
    const key = this.get('key');
    if (key) {
      map['path'] = ['like', '%' + key + '%'];
    }
    
    // 页码
    const page = this.get('page') || 1;
    // 每页显示数量
    const pageSize = this.get('pageSize') || 5;
    
    think.logger.debug(map);
    
    data = await this.modelInstance.where(map).page(page, pageSize).order('id desc').countSelect();
    return this.success(data);
  }
  
  // 图片上传
  async postAction() {
    think.logger.debug(this.post());
    
    const storage = this.post('storage') || 'local';
    
    let s = storage.toLowerCase();
    if (s === 'local') {
      const file = this.file('file'); // 七牛云单一文件上传必须使用token,file作为key
      if (!file) {
        return this.fail(1000, '请上传文件');
      }
      think.logger.debug(file);
      
      // 计算md5校验值，如果相同则不保存新的
      const buf = await fs.readFile(file.path);
      
      const checksum_md5 = think.md5(buf);
      
      let data = await this.model('image').where({
        md5: checksum_md5,
      }).find();
      
      if (!think.isEmpty(data)) {
        return this.success({
          'id': data.id,
          'type': 'exist',
        }, '上传文件已经存在，使用已经存在的文件。');
      }
      
      // 文件不存在
      // path.extname获取文件后缀名，可做上传控制
      const extname = path.extname(file.name);
      const filename = path.basename(file.path);
      const basename = think.md5(filename) + extname;
      const date = new Date();
      const year = date.getFullYear();
      const month = (date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1);
      const savepath = '/uploads/' + year + '/' + month + '/' + basename;
      const filepath = path.join(think.ROOT_PATH, 'www' + savepath);
      
      think.mkdir(path.dirname(filepath));
      await fs.rename(file.path, filepath);
      
      const row = await this.model('config').where({
        name: 'site',
      }).find();
      
      let config = {};
      if (!think.isEmpty(row)) {
        config = JSON.parse(row.value);
      }
      
      const id = await this.model('image').add({
        'base_url': config.url,
        'path': savepath,
        'storage': 'local',
        'md5': checksum_md5,
        'create_time': Math.round((new Date()).getTime() / 1000),
      });
      // await this.hook('upload', data);
      return this.success({
        'id': id,
        'type': 'add',
      }, '上传成功');
    } else if (s === 'qiniu') {
      {
        //七牛云，目前无法判断文件是否已经存在
        
        const data = this.post();
        
        const id = await this.model('image').add({
          ...data,
          'storage': 'qiniu',
          // md5: checksum_md5,
          'create_time': Math.round((new Date()).getTime() / 1000),
        });
        data.id = id;
        
        await this.hook('upload', data);
        return this.success({
          'id': id,
          'type': 'add',
        }, '上传成功');
      }
    }
  }
};
